angular.module('logincontrollers', [])
  .controller('GuideCtrl', function ($scope, $state,Member,Storage) {
    var currentIndex = 0;
    $scope.slideChanged = function (index) {
      if (currentIndex == 2 && index == 0) {
       // Member.setFirstInLogin();//不是第一次到登录界面
        Storage.set("firstInAPP", "noFirstInAPP");
        $state.transitionTo('login');
      }
      currentIndex = index;
    }
    $scope.goToLogin = function () {
      //Member.setFirstInLogin();//不是第一次到登录界面
      Storage.set("firstInAPP", "noFirstInAPP");
      $state.transitionTo('login');
    }
  })
  //广告页
  /*.controller('AdCtrl',function($scope,$timeout,$state,ENV,Member,Storage){
      $scope.picPath = ENV.picPath;
      var result = Member.getAdImgJson();
      $scope.adImg = result.au_advert_url;
      $scope.$on('$ionicView.beforeEnter',function(){
        var info = Storage.get("memberLoginInfo");
        var memberStorage = Storage.get('member');
        $timeout(function(){
          if(info && info!=null && info!=''){
            if(memberStorage && memberStorage.member_id){
              $state.transitionTo('tab.discoverIndex');
            }else{
              Member.setFirstInLogin();//不是第一次到登录界面
              $state.transitionTo('login');
            }
          }else{
            Member.setFirstInLogin();//不是第一次到登录界面
            $state.transitionTo('login');
          }
        },2000);
      });
  })*/
//登录的Controller
  .controller('LoginCtrl', function ($scope, $state, $cordovaFile, $timeout,$cordovaNetwork, $ionicLoading, Loading, $ionicPlatform, $resource, Member, ENV, Storage, Toast, ShareService) {
    $scope.member = {
      username: '',
      password: '',
      keepPwd: true
    };

    $scope.showPlatformState = {
      showQQ: false,
      showWeChat: false,
      showWeiBo: false,
      showText: false
    };
    $scope.$on('ShareService.QQInstalled', function () {
      checkInfo();
    });
    $scope.$on('ShareService.WeiBoInstalled', function () {
      checkInfo();
    });
    $scope.$on('ShareService.WeixinInstalled', function () {
      checkInfo();
    });
    checkInfo = function () {
      $scope.showPlatformState.showQQ = ShareService.getIsQqInstalled();
      $scope.showPlatformState.showWeChat = ShareService.getIsWeChatInstalled();
      $scope.showPlatformState.showWeiBo = ShareService.getIsWeiBoInstalled();
      if ($scope.showPlatformState.showQQ || $scope.showPlatformState.showWeChat || $scope.showPlatformState.showWeiBo) {
        $scope.showPlatformState.showText = true;
        ShareService.setIsShowShareWindow();
      }
    };

 /*   $scope.$on('Member.AdImgUpdated',function(){
        var adImgJson = Member.getAdImgJson();
        if(adImgJson.haveAd){
          $state.go('ad');
        }else{
          var info = Storage.get("memberLoginInfo");
          var memberStorage = Storage.get('member');
          if(info && info!=null && info!=''){
            if(memberStorage && memberStorage.member_id){
              $state.transitionTo('tab.discoverIndex');
            }else{
              $state.transitionTo('login');
            }
          }else{
            $state.transitionTo('login');
          }
        }
    });*/
    $scope.$on('$ionicView.beforeEnter', function () {
      //判断memberLoginInfo是否不为空
      if (Storage.get("firstInAPP") == '' || Storage.get("firstInAPP") == undefined) {
        $state.go('guide');
      } else {
        var info = Storage.get("memberLoginInfo");
        var memberStorage = Storage.get('member');
        if(info && info!=null && info!=''){
          if(memberStorage && memberStorage.member_id){
            $state.transitionTo('tab.discoverIndex');
          }else{
            $state.transitionTo('login');
          }
        }else{
          $state.transitionTo('login');
        }
       /* //加载广告页
        if(Member.getIsFirstInLogin()){
          Member.findAdImg();
        }*/
      }
      document.addEventListener("deviceready", function () {
        //检测第三方登录平台
        ShareService.checkQqIsInstalled();
        ShareService.checkWechatIsInstalled();
        ShareService.checkWeiBoIsInstalled();
      }, false);
      //创建winelife文件夹
      if (ionic.Platform.isAndroid()) {
        $cordovaFile.createDir(cordova.file.externalRootDirectory, "winelife", false)
          .then(function (success) {
          }, function (error) {
          });
      }
    });
    //重置界面的输入框内容
    function reset() {
      $scope.member = {
        username: '',
        password: '',
        keepPwd: true
      };
    }
    //跳转到注册界面
    $scope.go2register = function () {
      $state.go('register');
      $scope.member.username = '';
      $scope.member.password = '';
      $scope.member.keepPwd = true;
      Member.setFirstInLogin();//不是第一次到登录界面
    };
    //跳转到忘记密码界面
    $scope.go2lostPwd = function () {
      $state.go('lostPwd');
      $scope.member.username = '';
      $scope.member.password = '';
      $scope.member.keepPwd = true;
      Member.setFirstInLogin();//不是第一次到登录界面
    };

    //处理用户登录操作
    $scope.userLogin = function () {
      //判断用户名或者密码是否为空
      if ($scope.member.username == '') {
        Toast.showMessage('手机号码不能为空');
      } else if ($scope.member.password == '') {
        Toast.showMessage('密码不能为空');
      } else {
        //执行登录
        $scope.networkOk = false;
        Member.login($scope.member.username, $scope.member.password);
        Loading.showLoading();
        $timeout(function () {
          if (!$scope.networkOk) {
            Loading.hideLoading();
            Toast.showMessage("网络异常，请稍后再试....");
          }
        }, 10000);
      }
    };

    //当service访问网络成功时，调用该方法
    $scope.$on('Member.loginUpdated', function () {
      Loading.hideLoading();
      $scope.networkOk = true;
      var result = Member.getLoginInfo();
      if (result.loginStatus == false) {
        //登陆失败
        Toast.showMessage(result.loginMsg);
      } else if (result.loginStatus == true) {
        //登录成功，保存member_id到缓存中
        Storage.set('member', result);
        if ($scope.member.keepPwd) {
          //若点击“记住密码”，则将密码保存到缓存的member中
          Storage.set('memberLoginInfo', $scope.member);
        }
        reset();
        $state.transitionTo('tab.discoverIndex');  //路由跳转到发现首页
      }
    });

    /* ==================== QQ登陆操作 ==== begin ========================  */
    //处理点击QQ登录的操作
    $scope.go2QqLogin = function () {
      Loading.showLoading();
      var checkClientIsInstalled = 1;//默认值是 0,仅仅针对 iOS平台有效![]()
      YCQQ.ssoLogin(function (args) {
        //获取到 access_token 和 userid 存放在数据库中
        Member.qqLogin(args.userid, args.access_token);
      }, function (failReason) {
        Loading.hideLoading();
        Toast.showMessage("第三方登录失败");
      }, checkClientIsInstalled);
      Member.setFirstInLogin();//不是第一次到登录界面
    };

    //接收到第三方登录的后台处理数据
    $scope.$on('Member.qqLogin', function () {
      var result = Member.getQqLoginInfo();
      Loading.hideLoading();
      var status = result.loginStatus;
      if (!status) {
        Toast.showMessage(result.loginMsg);
      } else {
        if (result.loginType == "firstLoginFromOther") {
          Storage.set('member', result);
          $state.go('bindMember');  //绑定账号界面
        } else if (result.loginType == "loginByBindAccount") {
          Storage.set('member', result);
          $state.go('tab.discoverIndex');  //跳转到发现界面
        }
      }
    });
    /* ==================== QQ登陆操作 ==== end ========================  */


    /* ==================== 微信登陆操作 ==== begin ========================  */
    $scope.go2WechatLogin = function () {
      Loading.showLoading();
      var scope = "snsapi_userinfo";
      Wechat.auth(scope, function (response) {
        // 需要使用返回的response.code去获取access_token
        var getCode = response.code;
        var getUrl = "https://api.weixin.qq.com/sns/oauth2/access_token";
        var getTokenUrl = $resource(getUrl);
        getTokenUrl.get(
          {
            appid: ENV.weixinAppId,
            secret: ENV.weixinAppSecret,
            code: getCode,
            grant_type: 'authorization_code'
          },
          function (data) {
            var openid = data.openid;
            Member.weixinLogin(openid);
            Loading.hideLoading();
          }, function (err) {
            //进行登录操作
            Loading.hideLoading();
            Toast.showMessage("第三方登录失败");
          });
      }, function (reason) {
        Loading.hideLoading();
        Toast.showMessage("第三方登录失败");
      });
      Member.setFirstInLogin();//不是第一次到登录界面
      $timeout(function(){
        Loading.hideLoading();
      },3000);
    };

    $scope.$on('Member.weixinLogin', function () {
      var result = Member.getWeixinLoginInfo();
      var status = result.loginStatus;
      Loading.hideLoading();
      if (!status) {
        Toast.showMessage(result.loginMsg);
      } else {
        if (result.loginType == "firstLoginFromOther") {
          Storage.set('member', result);
          $state.go('bindMember');  //绑定账号界面
        } else if (result.loginType == "loginByBindAccount") {
          Storage.set('member', result);
          $state.go('tab.discoverIndex');  //跳转到发现界面
        }
      }
    });
    /* ==================== 微信登陆操作 ==== end ========================  */


    /* ==================== 微博登陆操作 ==== begin ========================  */
  //处理点击微博登录的操作
    $scope.go2WeiBoLogin = function () {
      Loading.showLoading();
      YCWeibo.ssoLogin(function (args) {
        //获取到 access_token 和 userid 存放在数据库中
        Member.weiBoLogin(args.userid, args.access_token);
      }, function (failReason) {
        Loading.hideLoading();
        Toast.showMessage("第三方登录失败");
      });
      Member.setFirstInLogin();//不是第一次到登录界面
    };

  //接收到第三方登录的后台处理数据
    $scope.$on('Member.weiBoLogin', function () {
      var result = Member.getWeiBoLoginInfo();
      Loading.hideLoading();
      var status = result.loginStatus;
      if (!status) {
        Toast.showMessage(result.loginMsg);
      } else {
        if (result.loginType == "firstLoginFromOther") {
          Storage.set('member', result);
          $state.go('bindMember');  //绑定账号界面
        } else if (result.loginType == "loginByBindAccount") {
          Storage.set('member', result);
          $state.go('tab.discoverIndex');  //跳转到发现界面
        }
      }
    });
    /* ==================== 微博登陆操作 ==== end ========================  */

  })
//注册的Controller
  .controller("RegisterCtrl", function ($scope, $state, $interval, $timeout, $ionicLoading, Loading, $ionicPlatform, Toast, Member, Storage) {
    $scope.member = {
      username: '',
      password: '',
      repassword: '',
      verifyCode: '',
      agreeService: false
    };

    $scope.verifyCodFromBack = "";
    $scope.verifyCodeBtnText = "获取验证码";
    $scope.countdown = 60;


    //清空数据
    function clearData() {
      $scope.member = username = '';
      $scope.member.password = '';
      $scope.member.repassword = '';
      $scope.member.verifyCode = '';
      $scope.member.agreeService = false;
    }

    //服务协议
    $scope.go2Procotol = function () {
      $state.go("procotol");
    };

    $scope.clickAgreeService = function () {
      $scope.member.agreeService = !$scope.member.agreeService;
    };

    $scope.clickGetVerifyCode = function () {
      var reg = /[1][3,4,5,8][0-9]{9}/;
      //var reg = new RegExp('[1][3,4,5,8][0-9]{9}');
      if ($scope.member.username == "") {
        Toast.showMessage("请输入手机号码，再点击获取验证码");
      }
      else if (!$scope.member.username.match(reg)) {
        Toast.showMessage("手机号码格式不正确，请重新输入");
      }
      else {
        //获取验证码
        Member.getVerifyCode($scope.member.username);
        $scope.isBtnDisabled = true;
        //设置定时器
        var myTime = setInterval(function () {
          $scope.verifyCodeBtnText = ($scope.countdown--) + '秒';
          $scope.$digest(); // 通知视图模型的变化
        }, 1000);

        // 停止定时器
        setTimeout(function () {
          clearInterval(myTime);
          $scope.countdown = 60;
          $scope.verifyCodeBtnText = "重新获取验证码";
          $scope.isBtnDisabled = false;
          $scope.$digest(); // 通知视图模型的变化
        }, 61000);
      }
    };


    $scope.$on('Member.getVerifyCode', function () {
      var result = Member.getVerifyCodeInfo();
      if (result.resultStatus) {
        $scope.verifyCodFromBack = result.verifyCode;
      } else {
        Toast.showMessage(result.resultMsg);
      }
    });


    //注册
    $scope.userRegister = function () {
      if ($scope.member.username == '') {
        Toast.showMessage("手机号码不能为空");
      } else if ($scope.member.password == '') {
        Toast.showMessage("密码不能为空");
      } else if ($scope.member.repassword == '') {
        Toast.showMessage("确认密码不能为空");
      } else if ($scope.member.verifyCode == '') {
        Toast.showMessage("验证码不能为空");
      } else if ($scope.member.password != $scope.member.repassword) {
        Toast.showMessage("两次输入的密码不一致");
      } else if ($scope.member.verifyCode != $scope.verifyCodFromBack) {
        Toast.showMessage("验证码不正确");
      } else if ($scope.member.agreeService == false) {
        Toast.showMessage("请同意服务协议");
      } else {
        Member.register($scope.member.username, $scope.member.password, $scope.member.repassword, $scope.member.verifyCode);
        $scope.verifyCodFromBack = "";
        Loading.showLoading();
        $timeout(function () {
          Loading.hideLoading();
          if (!$scope.networkOk) {
            Toast.showMessage("网络异常，请稍后再试....");
            clearData();
          }
        }, 5000);
      }
    };
    //当service访问网络成功时，调用该方法
    $scope.$on('Member.registerUpdated', function () {
      $scope.networkOk = true;
      var result = Member.getRegisterInfo();

      if (result.regitsterState == false) {//注册失败
        Loading.hideLoading();
        Toast.showMessage(result.registerMsg);
        clearData();
      } else {
        Member.login($scope.member.username, $scope.member.password);
        clearData();
      }
    });
    //当service访问网络成功时，调用该方法
    $scope.$on('Member.loginUpdated', function () {
      Loading.hideLoading();
      $scope.networkOk = true;
      var result = Member.getLoginInfo();
      if (result.loginStatus == false) {
        //登陆失败
        Toast.showMessage(result.loginMsg);
      } else if (result.loginStatus == true) {
        //登录成功，保存member_id到缓存中
        Storage.set('member', result);
        clearData();
        $state.transitionTo('tab.discoverIndex');  //路由跳转到发现首页
      }
    });
  })


  //忘记密码的Controller
  .controller("lostPwdCtrl", function ($scope, $timeout, $state, $ionicLoading, Loading, $ionicPlatform, Member, Toast, Storage) {
    $scope.member = {
      username: '',
      password: '',
      repassword: '',
      verifyCode: ''
    };

    //清空数据
    function clearData() {
      $scope.member.username = '';
      $scope.member.password = '';
      $scope.member.repassword = '';
      $scope.member.verifyCode = '';
    }

    $scope.verifyCodFromBack = "";
    $scope.verifyCodeBtnText = "获取验证码";
    $scope.countdown = 60;


    //触发点击获取验证码
    $scope.clickGetVerifyCode = function () {
      var reg = /[1][3,4,5,8][0-9]{9}/;
      if ($scope.member.username == "") {
        Toast.showMessage("请输入手机号码，再点击获取验证码");
        //需要验证电话号码的格式
      } else if (!$scope.member.username.match(reg)) {
        Toast.showMessage("手机号码格式不正确，请重新输入");
      }
      else {
        //获取验证码
        Member.getVerifyCode($scope.member.username);
        $scope.isBtnDisabled = true;

        //设置定时器
        var myTime = setInterval(function () {
          $scope.verifyCodeBtnText = '  ' + ($scope.countdown--) + '秒  ';
          $scope.$digest(); // 通知视图模型的变化
        }, 1000);

        // 停止定时器
        setTimeout(function () {
          clearInterval(myTime);
          $scope.countdown = 60;
          $scope.verifyCodeBtnText = "重新获取验证码";
          $scope.isBtnDisabled = false;
          $scope.$digest(); // 通知视图模型的变化
        }, 61000);
      }
    };


    $scope.$on('Member.getVerifyCode', function () {
      var result = Member.getVerifyCodeInfo();
      if (result.resultStatus) {
        $scope.verifyCodFromBack = result.verifyCode;
      } else {
        Toast.showMessage(result.resultMsg);
      }
    });


    $scope.resetPwd = function () {
      if ($scope.member.username == '') {
        Toast.showMessage("手机号码不能为空");
      } else if ($scope.member.password == '') {
        Toast.showMessage("密码不能为空");
      } else if ($scope.member.repassword == '') {
        Toast.showMessage("确认密码不能为空");
      } else if ($scope.member.verifyCode == '') {
        Toast.showMessage("验证码不能为空");
      } else if ($scope.member.verifyCode != $scope.verifyCodFromBack) {
        Toast.showMessage("验证码不正确");
      } else if ($scope.member.password != $scope.member.repassword) {
        Toast.showMessage("两次输入的密码不一致");
      } else {
        Member.resetPwd($scope.member.username, $scope.member.password, $scope.member.repassword, $scope.member.verifyCode);
        Loading.showLoading();

        $timeout(function () {
          Loading.hideLoading();
          if (!$scope.networkOk) {
            Toast.showMessage("网络异常，请稍后再试....");
            clearData();
          }
        }, 5000);
      }
    };


    $scope.$on('Member.resetPwdUpdated', function () {
      $scope.networkOk = true;
      $ionicLoading.hide();
      var result = Member.getResetPwdInfo();
      if (!result.resetPwdState) {
        Toast.showMessage(result.resetPwdMsg);
      } else {
        Member.login($scope.member.username, $scope.member.password);
        clearData();
      }
    });
    $scope.$on('Member.loginUpdated', function () {
      Loading.hideLoading();
      $scope.networkOk = true;
      var result = Member.getLoginInfo();
      if (result.loginStatus == false) {
        //登陆失败
        Toast.showMessage(result.loginMsg);

      } else if (result.loginStatus == true) {
        //登录成功，保存member_id到缓存中
        Storage.set('member', result);
        clearData();
        $state.transitionTo('tab.discoverIndex');  //路由跳转到发现首页
      }
    });
  })
//服务协议的Controller
  .controller("procotolCtrl", function ($scope, $ionicLoading, $ionicPlatform, Toast, Member, History) {

    $scope.procotol = '';

    //获取服务协议
    Member.getProcotol();
    //获取服务协议成功后，执行如下方法
    $scope.$on('Member.procotolUpdated', function () {
      var result = Member.getProcotolInfo();
      if (result.protocolStatus == false) {
        Toast.showMessage(result.protocol);
      } else {
        $scope.procotol = result.protocol;
      }
    });

    $scope.goBack = function () {
      History.goback();
    }
  });
